package com.google.code.head2head.gwtmodules.client;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class FileUploadPanel extends FormPanel {

	public FileUploadPanel() {
		
		// Create a FormPanel and point it at a service.
		this.setAction("fileUploadServlet");
		
		final HTML text=new HTML("");

		// Because we're going to add a FileUpload widget, we'll need to set the
		// form to use the POST method, and multipart MIME encoding.
		this.setEncoding(FormPanel.ENCODING_MULTIPART);
		this.setMethod(FormPanel.METHOD_POST);

		// Create a panel to hold all of the form widgets.
		VerticalPanel panel = new VerticalPanel();
		this.setWidget(panel);

		// Create a FileUpload widget.
		final FileUpload upload1 = new FileUpload();
		upload1.setName("uploadImage1");
		
		final FileUpload upload2 = new FileUpload();
		upload2.setName("uploadImage2");

		panel.add(text);
		panel.add(upload1);
		panel.add(upload2);

		// Add a 'submit' button.
		panel.add(new Button("Submit", new ClickListener() {
			public void onClick(Widget sender) {
				submit();
			}
		}));
		
		
		this.addFormHandler(new FormHandler() {
			public void onSubmit(FormSubmitEvent event)
			{
				text.setHTML("Uploading data to server...");
				
				if (upload1.getFilename().length() == 0)
				{
					Window.alert("You did not specify a filename!");
					event.setCancelled(true);
				}
				else if (!upload1.getFilename().toLowerCase().endsWith(".jpg"))
				{
					Window.alert("Please specify a jpg file ending with '.jpg'.");
					event.setCancelled(true);
				}
			}

			public void onSubmitComplete(FormSubmitCompleteEvent event)
			{
				Window.alert(event.getResults());
				text.setHTML("Data uploaded");
			}
		});

	}
}
